package org.spring.springboot.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.spring.springboot.dao.biz.UpLoadDao;
import org.spring.springboot.entity.IntervieweeManage;
import org.spring.springboot.exception.CommonBizException;
import org.spring.springboot.exception.ExpCodeEnum;
import org.spring.springboot.listenner.EasyExcelListenner;
import org.spring.springboot.server.ExportImportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@Api(tags = "数据库、Excel导入导出")
@RequestMapping("/ExprotImport")
public class ExprotImportController {
    @Autowired
    private ExportImportService exportImportService;
    @Autowired
    private UpLoadDao upLoadDao;

    @PostMapping("/excelExport")
    @ApiOperation(value = "出门单数据库导出到excel")
    public String excelOutput(){
        String path="D:\\Export.xls";
        Integer count = exportImportService.getCount();
        ExcelWriter excelWriter = EasyExcel.write(path, IntervieweeManage.class).build();
        int sheetNum = count % 5000 == 0 ? count / 5000 : count / 5000 + 1;
        for (int i=1;i<=sheetNum;i++){
            List<IntervieweeManage> listByPage = exportImportService.getListByPage(1);
            WriteSheet sheet = EasyExcel.writerSheet("第【"+i+"】批数据").build();
            excelWriter.write(listByPage, sheet);
        }
        excelWriter.finish();
        return "数据库导出成功";
    }

    @PostMapping("/datebaseImport")
    @ApiOperation(value = "出门单excel导入到数据库")
    public String datebaseImport(MultipartFile file) throws Exception {
        if (!file.getOriginalFilename().contains(".xlsx")&&!file.getOriginalFilename().contains(".xls")) {
            throw new CommonBizException(ExpCodeEnum.NOT_EXCEL);
        }
//        upLoadDao.delete();
        EasyExcel.read(file.getInputStream(), IntervieweeManage.class, new EasyExcelListenner(upLoadDao)).sheet().doRead();
//        ReadSheet readSheet1 = EasyExcel.readSheet(0).build();
//        excelReader.read(readSheet1);
//        excelReader.finish();
        return "解析成功,并入库";
    }

}
